package com.gexiaobao.pigeon.ui.fragment.mine.pigeon.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.inputmethod.InputMethodManager
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.widget.AppCompatEditText
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.VisitMemberListResponse
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.databinding.ActivityVisitationDataPrintingBinding
import com.gexiaobao.pigeon.permissions.PermissionInterceptor
import com.gexiaobao.pigeon.ui.dialog.RxDialogMemberList
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityPrintVisit
import com.gexiaobao.pigeon.viewmodel.ShedPigeonViewModel
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.yzq.zxinglibrary.android.CaptureActivity
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivity
import java.util.Timer
import java.util.TimerTask

/**
 * @Author      : hxw
 * @Date        : 2025/1/16 14:22
 * @Describe    : 探视打印
 */
class ActivityVisitationDataPrinting : BaseActivity<ShedPigeonViewModel, ActivityVisitationDataPrintingBinding>() {

    private var printCode = ""
    private var raceId = 0

    private val scanLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        when (result.resultCode) {
            RESULT_OK -> {
                val userId = result.data?.getStringExtra(com.yzq.zxinglibrary.common.Constant.CODED_CONTENT)
                if (userId != null && isInteger(userId.toString())) {
                    showLoading(getString(R.string.loading))
                    mViewModel.getVisitMemberNoListII(raceId, userId.toInt())
                } else {
                    RxToast.warning("请扫描正确的个人二维码")
                }
            }

            RESULT_CANCELED -> {}
            else -> println("未知操作")
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        raceId = intent.getIntExtra("raceId", 0)
        mDatabind.includeBar.tvTitle.text = "探视打印"

        printCode = KvUtils.decodeString(Constant.PRINT_CODE)
        mDatabind.etPrintCode.setText(printCode)
        mDatabind.etPrintCode.isEnabled = printCode.isEmpty()
        if (printCode.isEmpty()) {
            //获取edittext焦点 并弹出软键盘
            showSoftInputFromWindow(mDatabind.etPrintCode)
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.btnSureVisitData, mDatabind.includeBar.ivBack, mDatabind.tvChangeStation) {
            when (it) {
                mDatabind.tvChangeStation -> {
                    mDatabind.etPrintCode.isEnabled = true
                    mDatabind.etPrintCode.setText("")
                    KvUtils.encode(Constant.PRINT_CODE, "")
                    mDatabind.etPrintCode.requestFocus()
                    showSoftInputFromWindow(mDatabind.etPrintCode)
                }

                mDatabind.includeBar.ivBack -> finish()
                mDatabind.btnSureVisitData -> permissionRequest()
            }
        }
    }

    override fun createObserver() {
        super.createObserver()
        /** 获取单用户下探视棚号列表(打印) */
        mViewModel.memberNoListResult.observe(this) {
            if (it != null && it.isEmpty()) {
                showMessage("暂不是本场比赛会员")
                return@observe
            }
            if (it.list.size == 1) {
                val printCode = mDatabind.etPrintCode.text.toString().trim()
                val memberId = it.list[0].memberId
                startActivity<ActivityPrintVisit>("memberId" to memberId, "raceId" to raceId, "printCode" to printCode)
            } else {
                val memberList: ArrayList<VisitMemberListResponse.ListBean> = arrayListOf()
                memberList.addAll(it.list)
                showMemberDialog(memberList)
            }
        }
    }

    /**
     * EditText获取焦点并显示软键盘
     */
    private fun showSoftInputFromWindow(editText: AppCompatEditText) {
        editText.isFocusable = true
        editText.isFocusableInTouchMode = true
        editText.requestFocus()
        Timer().schedule(object : TimerTask() {
            override fun run() {
                val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
            }
        }, 200)
    }

    private fun showMemberDialog(memberList: ArrayList<VisitMemberListResponse.ListBean>) {
        val dialog = RxDialogMemberList(this)
        dialog.setAdapterData(memberList)
        val printCode = mDatabind.etPrintCode.text.toString().trim()
        dialog.setOnClickListener(object : RxDialogMemberList.OnItemClickListener {
            override fun onItemClick(position: Int, id: Int) {
                startActivity<ActivityPrintVisit>("memberId" to id, "raceId" to raceId, "printCode" to printCode)
                dialog.dismiss()
            }
        })
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun permissionRequest() {
        val code = mDatabind.etPrintCode.text.toString().trim()
        KvUtils.encode(Constant.PRINT_CODE, code)
        if (code.isEmpty()) {
            RxToast.warning("未输入打印识别码")
            return
        }
        XXPermissions.with(this)
            .permission(Permission.CAMERA)
            .interceptor(PermissionInterceptor())
            .request { _, allGranted ->
                if (allGranted) {
                    val intent = Intent(this@ActivityVisitationDataPrinting, CaptureActivity::class.java)
                    scanLauncher.launch(intent)
                }
            }
    }
}